/**
 * SysContextLoaderListener.java 
 * Copyright © 2015-3015, 杭州泊享网络科技有限公司
 * 
 * @author Liu Tao
 * @create 2013年8月14日
 */
package com.pshare.artemis.framework.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.web.context.ContextLoaderListener;

import com.pshare.artemis.framework.constants.SeaxConstants;
import com.pshare.tools.PayPropertyUtils;
import com.pshare.util.DBPropertyUtils;
import com.pshare.util.HttpUtils;
import com.pshare.util.PropertyLoader;
import com.pshare.util.RedisPropertyUtils;
import com.pshare.util.SearchPropertyUtils;
import com.pshare.util.SysPropertyUtils;
import com.pshare.util.WXSignUtils;

/**
 * 上下文加载监听器, 从Spring继承而来. 该类的作用可初始化一些参数
 */
public class SysContextLoaderListener extends ContextLoaderListener {

	private static final Logger logger = Logger.getLogger(SysContextLoaderListener.class);

	@Override
	public void contextInitialized(ServletContextEvent event) {
		ServletContext ctx = event.getServletContext();
		String webRootRealPath = ctx.getRealPath("/");

		logger.info("===============================================");
		logger.info("开始加载上下文...");
		logger.info("===============================================");

		logger.info("工程所在路径：" + webRootRealPath);
		
		String location = ctx.getInitParameter("appConfigLocation");
		initConf(location);
		super.contextInitialized(event);
		initSysInfo();
		intWXAccessToken();
		logger.info("===============================================");
		logger.info("加载上下文成功...");
		logger.info("===============================================");
	}
	
	public void initConf(String location) {
		SysPropertyUtils.setPropLocation(location + SeaxConstants.SYSPROPERTIES_FILE);
		DBPropertyUtils.setPropLocation(location + SeaxConstants.DBPROPERTIES_FILE);
		RedisPropertyUtils.setPropLocation(location + SeaxConstants.REDISPROPERTIES_FILE);
		PayPropertyUtils.setPropLocation(location + SeaxConstants.PAYPROPERTIES_FILE);
		SearchPropertyUtils.setPropLocation(location + SeaxConstants.SEARCHPROPERTIES_FILE);
		PropertyLoader.setPropLocation(location);
	}
	
	

	public void initSysInfo() {
		
	}
	
	/**
	 * 微信ACCESS_TOKEN
	 */
	
	public void intWXAccessToken() {
		 String appid=SysPropertyUtils.getProperty("wx.appid");
		 String appsecret=SysPropertyUtils.getProperty("wx.appsecret");
		 String host=SysPropertyUtils.getProperty("wx.accesstoken_host");
		 String url=host+"?grant_type=client_credential&appid="+appid+"&secret="+appsecret;
		 JSONObject object=HttpUtils.getJsonInUrlGet(url);
		 String accessToken="";
		 if(object!=null){
			 accessToken=object.getString("access_token");
		 }
		 WXSignUtils.ACCESS_TOKEN=accessToken;
		 logger.info("url="+url+",,,accessToken="+accessToken);
	}
	
}
